﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Lib;

namespace Client
{
    public partial class FrmMain : Form
    {
        //NEED TO BE RE-DESIGN
        public Dictionary<string, FrmChat> lst_chat_form;

        Byte[] buffer = new Byte[2048];
        bool is_list_requested = false;

        public FrmMain()
        {
            InitializeComponent();
            lst_chat_form = new Dictionary<string, FrmChat>();
        }

        private void ReloadFriendList(string[] lstnick)
        {
            this.Invoke(new Action(() =>
            {
                lvFriendsList.Items.Clear();

                for (int i = 1; i < lstnick.Length; ++i)
                {
                    ListViewItem lvi = new ListViewItem(lstnick[i]);
                    lvFriendsList.Items.Add(lvi);
                }
            }));
        }

        private void OnReceive(byte[] data)
        {
            if (!is_list_requested)
            {
                string resp = Lib.Helpper.GetString(data);
                string[] lst = resp.Split(':');

                if (lst.Length > 1)
                {
                    ReloadFriendList(lst);
                }

                is_list_requested = true;
            }
            else
            {
                string str = Lib.Helpper.GetString(data);
                string un = str.Split(':')[0];

                FrmChat frm = null;
                try {
                    frm = lst_chat_form[un];
                } catch {
                    frm = new FrmChat(un, this);
                    frm.Show();
                    lst_chat_form.Add(un, frm);
                }

                frm.AppendMessage(str);
            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            FrmLogin login = new FrmLogin();
            login.ShowDialog(this);

            Lib.Client c = Lib.Client.GetInstance();
            c.OnReceive = OnReceive;

            c.RequestList();
        }

        private void lvFriendsList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvFriendsList.SelectedItems.Count == 0) return;

            string name = lvFriendsList.SelectedItems[0].Text;

            FrmChat frmChat = new FrmChat(name, this);
            lst_chat_form.Add(name, frmChat);
            frmChat.Show();

            int i = 0;
            i++;
        }
    }
}
